import PropTypes from 'prop-types';
import PureRenderMixin from "react-addons-pure-render-mixin"
import React, {Component} from 'react';
import D3Chart from '../D3Chart'
import d3 from './d3';
import './bar.scss';
import T from 'utils/T';


@T.decorator.propTypes({
    data: PropTypes.array,
    option: PropTypes.object
})
export default class Pie extends D3Chart {
    setDefaultOptions(){
        return {
            width: 400,
            height: 400,
            left:30,
            right:30,
            top:20,
            bottom:30,
            rectPadding: 4,
            color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3']

        }
    }

    /**
     * 标准化数据格式
     */
    normalize() {
        const dataInit = this.props.data;
        this.xData = [];
        this.yData = [];
        this.data = dataInit.map(item => {
            this.xData.push(item.x);
            this.yData.push(item.value);
            return item;
        });
    }

    drawChart(){

        const options = this.getOptions();
        //在 wrapper 里添加一个 SVG 画布
        this.chart = d3.select(this.wrapper)     //选择文档中的wrapper元素
            .append('svg')          //添加一个svg元素
            .attr('width', '100%')       //设定宽度
            .attr('height', options.height)    //设定高度
            .style('border', '1px solid #ccc');
        //画布周边的空白
        let padding = {left:options.left, right:options.right, top:options.top, bottom:options.bottom};


        // 定义一个布局，
        const pie = d3.pie();
        // 饼图数据，v5和v3版本写法差别较大
        const piedata = pie(this.data.map(item => item.value));

        // 圆弧生成器
        const arc = d3.arc()
            .innerRadius(0)
            .outerRadius(100);

        let arcs = this.chart.selectAll("g")
            .data(piedata)
            .enter()
            .append("g")
            .attr("transform","translate("+ (options.width/2) +","+ (options.width/2 - 50) +")");

        arcs.append("path")
            .attr("fill",function(d,i){
                return options.color[i];
            })
            .attr("d",function(d){
                return arc(d);   //调用弧生成器，得到路径值
            });


        arcs.append("text")
            .attr("transform",function(d){
                return "translate(" + arc.centroid(d) + ")";
            })
            .attr("text-anchor","middle")
            .text(function(d){
                return d.data + '%';
            });

    }
}
